home *** CD-ROM | disk | FTP | other *** search
- Path: news1.h1.usa.pipeline.com!usenet
- From: grantp@usa.pipeline.com(Pete)
- Newsgroups: comp.lang.c++
- Subject: Re: dynamic memory allocation
- Date: 28 Jan 1996 15:40:36 GMT
- Organization: Kalevi, Inc.
- Message-ID: <4eg5dk$5i3@news1.usa.pipeline.com>
- NNTP-Posting-Host: pipe4.h1.usa.pipeline.com
- X-PipeUser: grantp
- X-PipeHub: usa.pipeline.com
- X-PipeGCOS: (Pete)
- X-Newsreader: Pipeline USA v3.3.0
-
- On Jan 28, 1996 00:04:25 in article <dynamic memory allocation>, 'Luciano
- Brocchieri <luciano@gnomic.stanford.edu>' wrote:
-
-
- >From main I am passing a pointer int *p to a function function(p,&n)
- >which allocates memory to it:
- >p=(int *)malloc(n,sizeof(int));
- >My problem is: how do I let main know of the existence of the
- >allocated memory? My solution is writing in main:
- >p=(int *)realloc(p,n*sizeof(int));
- >right after the function call, before something else gets written
- >on it, which, though effective, doesn't seem very elegant. Besides,
- >functions like malloc(), strdup(), etc., seem to be able to let
- >the calling function know of the allocated memory. What is the
- >right procedure? Any suggestion will be greatly appreciated.
- >Thanks a lot,
- >
- Not quite clear on the constraints involved, also, the question
- is posted to comp.lang.c++ but looks like this might be a straight
- C project???
-
- Anyway, in either language, it would be preferable to return
- the pointer to the newly allocated memory; e.g.,
-
- int * function(int n)
- {
- int * p = malloc(n * sizeof(int));
- ... dowhateverelse
- return p;
- }
- Of course, if you are writing C++ , the first line should read:
- int * p = new int[n];
-
- Then, in your calling routine you can just call
- int * array = function(500);
-
- Now, if you want function to return some other value and
- still want to get at the pointer to the memory allocated, in
- C it's something like:
-
- int function(int n, int ** p)
- {
- *p = malloc(n * sizeof(int));
- return whatever;
- }
-
- and in calling routine:
-
- int * buffer;
- int x = function(500, &buffer);
-
- C++ solution is similar -- you can use the C way in both.
- --
- Pete Grant
- Kalevi, Inc.
- Object Oriented Software Development
-